<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--查询筛选框-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryForm" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="queryForm.name"
              placeholder="请输入商品名称"
              clearable
              size="small"
              style="width: 180px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="上架状态" prop="shelf">
            <el-select
              v-model="queryForm.shelf"
              placeholder="请输入上架状态"
              clearable
              size="small"
              style="width: 180px"
            >
              <el-option
                v-for="item in shelfOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-has-perm="['mall_goodsSpu:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-document"
              size="mini"
              @click="handleShelf('on')"
              :disabled="multiple"
              v-has-perm="['mall_goodsSpu:onShelf']"
            >批量上架
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-document"
              size="mini"
              @click="handleShelf('off')"
              :disabled="multiple"
              v-has-perm="['mall_goodsSpu:offShelf']"
            >批量下架
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="handleQuery"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :header-cell-style="thStyleFun" :cell-style="cellStyleFun"
                  :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50"/>
          <el-table-column label="商品名称" prop="name" width="160px" show-overflow-tooltip/>
          <el-table-column label="商品图片" prop="picList" width="120px">
            <template slot-scope="scope">
              <el-image style="width: 120px; height: 50px" :src="scope.row.picList[0]" fit="contain"
                        :preview-src-list="scope.row.picList"/>
            </template>
          </el-table-column>
          <el-table-column label="类别" prop="categoryId" width="80px" show-overflow-tooltip/>
          <el-table-column label="卖点" prop="sellPoint" width="260px" show-overflow-tooltip/>
          <el-table-column label="销售价" prop="salesPrice" width="80px">
          </el-table-column>
          <el-table-column label="市场价" prop="marketPrice" width="80px"/>
          <el-table-column label="成本价" prop="costPrice" width="80px"/>
          <el-table-column label="库存" prop="stock" width="80px"/>
          <el-table-column label="商品编码" prop="spuCode" width="80px" show-overflow-tooltip/>
          <el-table-column label="虚拟销量" prop="saleNum" width="80px" show-overflow-tooltip/>
          <el-table-column label="是否上架" width="100px">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.shelf"
                :active-value="1"
                :inactive-value="0"
                @change="handleShelfChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="160"/>
          <el-table-column label="更新时间" prop="createTime" width="160"/>
          <el-table-column label="操作" min-width="100px" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="detail"
                icon="el-icon-view"
                @click="handleUpdate(scope.row)"
                v-has-perm="['mall_goodsSpu:detail']"
              >详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryForm.cursor"
          :limit.sync="queryForm.limit"
          @pagination="_getGs"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-dialog-drag :title="title" :visible.sync="open" width="800px" append-to-body :before-close="reset">
      <el-form ref="form" :model="form" label-width="80px" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品图片" prop="picList">
              <el-image style="width: 150px;height: 150px" :src="form.picList[0]" fit="contain"
                        @click.native="uploadPhotos">
                <div slot="error" class="image-slot">
                  <img style="width:150px;height:150px;" src="@/assets/images/userImg.jpg"/>
                </div>
              </el-image>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入分类名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="categoryId">
              <el-input v-model="form.categoryId" placeholder="请输入类别"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="卖点" prop="sellPoint">
              <el-input v-model="form.sellPoint" placeholder="请输入卖点"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售价" prop="salesPrice">
              <el-input v-model="form.salesPrice" placeholder="请输入销售价"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="市场价" prop="marketPrice">
              <el-input v-model="form.marketPrice" placeholder="请输入市场价"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本价" prop="costPrice">
              <el-input v-model="form.costPrice" placeholder="请输入成本价"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input v-model="form.stock" placeholder="请输入库存"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="spuCode">
              <el-input v-model="form.spuCode" placeholder="请输入商品编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="虚拟销量" prop="saleNum">
              <el-input v-model="form.saleNum" placeholder="请输入虚拟销量"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否上架">
              <el-radio-group v-model="form.shelf">
                <el-radio v-for="item in shelfOptions"
                          :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime" v-show="title=='修改商品'">
              {{ form.createTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updateTime" v-show="title=='修改商品'">
              {{ form.updateTime }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <quill-editor v-model="form.description" style="height: 300px"></quill-editor>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 图片上传组件 -->
        <common-upload v-if='photo.dialogImgPath' ref='upload' @listenEvent='dialogImgPathClose'
                       :dialog="photo.dialogImgPath"
                       :save='photo.needSavePhoto' :photoid='photo.tableId' :random='photo.random'
                       :bucket='photo.bucket'
                       :type='photo.tableType'></common-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div slot="footer" class="dialog-footer">
        <span v-has-perm="['mall_goodsSpu:add']">
          <el-button type="primary" v-if="title=='添加商品'" @click="submitForm">确 定
          </el-button>
        </span>
          <span v-has-perm="['mall_goodsSpu:edit']">
          <el-button type="primary" v-if="title=='修改商品'" @click="submitForm">确 定
          </el-button>
        </span>
          <el-button @click="reset()">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addGs, changeGsShelf, getGs, pageGs, updateGs} from "@/api/mall/goodsSpu";
import {cellStyleFun, thStyleFun} from "@/utils/common";
import commonUpload from "@/components/Common/common-upload";

export default {
  name: "goodsSpu",
  components: {'common-upload': commonUpload},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      //上传图片
      photo: {
        dialogImgPath: false,
        needSavePhoto: false,
        tableId: '',
        tableType: '',
        random: '',
        bucket: '公有',
      },
      title: undefined,
      // 查询表单数据对象
      queryForm: {
        name: undefined,
        shelf: undefined,
        cursor: 1,
        limit: 20
      },
      // 总条数
      total: 0,
      list: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 表单
      form: {
        picList: []
      },
      open: false,
      // 上架状态
      shelfOptions: [
        {value: 1, label: '上架'},
        {value: 0, label: '下架'}
      ],
    }
  },
  methods: {
    uploadPhotos() {//上传图片按钮
      this.photo.tableId = this.form.id
      this.photo.dialogImgPath = true
      this.photo.tableType = '商品信息'
      if (!this.form.id) {
        this.photo.needSavePhoto = false//需要保存按钮
      } else {
        this.photo.random = parseInt((Math.random() * 9 + 1) * 100000000000)
        this.photo.needSavePhoto = true//需要保存按钮
      }
    },
    initPhotos() {
      this.photo.random = parseInt((Math.random() * 9 + 1) * 100000000000)
    },
    dialogImgPathClose() {//上传图片弹窗关闭
      this.photo.dialogImgPath = false
      console.log("upload", this.$refs.upload)
      console.log("photoList", this.$refs.upload.photoList)
      console.log("fileList", this.$refs.upload.fileList)
      if (this.form.id) {
        this.getGs(this.form.id)
      } else {
        this.form.picList = this.$refs.upload.photoList.map(value => value.url)
      }
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryForm.cursor = 1
      this._getGs()
    },
    // 获取商品信息列表
    _getGs() {
      pageGs(this.queryForm).then(({result: res}) => {
        this.total = res.total
        this.list = res.records
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 表单重置
    reset() {
      this.$refs['form'].resetFields()
      this.form = this.$options.data().form
      this.photo = this.$options.data().photo
      this.open = false
    },
    //上架状态
    shelfFormat(row, column) {
      return this.matchingLabel(this.shelfOptions, row.shelf)
    },
    // 上架状态修改
    async handleShelfChange(row) {
      let text = row.shelf === 1 ? "上架" : "下架";
      const confirm = await this.$confirm('确认要' + text + ' "  ' + row.name + '  " 商品信息吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err)
      if (confirm != 'confirm') {
        row.shelf = row.shelf === 0 ? 1 : 0
        return this.$message.info('取消操作')
      }
      changeGsShelf(Array.of(row.id), row.shelf).then((res) => {
        this.$message.success(text + "成功");
      }).catch(err => {
        row.shelf = row.shelf === 0 ? 1 : 0
      })
    },
    async handleShelf(type) {
      let text = type == 'on' ? '上架' : '下架';
      if (!this.ids.length) {
        this.$message.warning(`请选择需要${text}的商品`)
        return
      }
      let shelf = type == 'on' ? 1 : 0;
      const confirm = await this.$confirm(`确认要${text}这些商品信息吗?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err)
      if (confirm != 'confirm') {
        return this.$message.info('取消操作')
      }
      changeGsShelf(this.ids, shelf).then((res) => {
        this.$message.success(text + "成功");
        this.handleQuery()
      }).catch(err => {
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加商品";
      this.initPhotos()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getGs(row.id)
    },
    getGs(id) {
      getGs(id).then(({result: res}) => {
        this.form = res;
        this.open = true;
        this.title = "修改商品";
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      if (this.validForm("form")) {
        if (this.form.id != undefined) {
          updateGs(this.form).then(res => {
            this.$message.success("修改成功");
            this.open = false;
            this.getList();
          })
        } else {
          addGs(this.form).then(res => {
            this.$message.success("新增成功");
            this.open = false;
            this.getList();
          })
        }
      }
    },
    // 表格居中 (html中使用需要先声明)
    thStyleFun,
    // 表格居中 (html中使用需要先声明)
    cellStyleFun
  },
  created() {
    this.handleQuery();
  },
}
</script>

<style scoped>
</style>
